package com.skyblue.crawel.service;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

@Endpoint(id = "mythread")
@Component
public class MyThreadEndpoint {
	@ReadOperation
	public ThreadDumpDescriptor threadDump() {
		return new ThreadDumpDescriptor(Arrays
				.asList(ManagementFactory.getThreadMXBean().dumpAllThreads(true, true)));
	}
	
	/**
	 * A description of a thread dump. Primarily intended for serialization to JSON.
	 */
	public final class ThreadDumpDescriptor {
		
		private MyThreadDesc myThreadDesc ;
		private List<ThreadInfo> threads;

		private ThreadDumpDescriptor(List<ThreadInfo> threads) {
			if(myThreadDesc == null) {
				myThreadDesc = new MyThreadDesc();
			}
			this.threads = threads;
		}

		public MyThreadDesc getMyThreads() {
			myThreadDesc.threadStatus = new HashMap<String,String>();
			int i = 0;
			List<ThreadInfo> myThreads = new ArrayList<ThreadInfo>();
			for(ThreadInfo threadInfo:this.threads) {
				if(threadInfo.getThreadName().indexOf("taskExecutor") > -1) {
					i++;
					myThreads.add(threadInfo);
					myThreadDesc.threadStatus.put(threadInfo.getThreadName(),threadInfo.getThreadState().name());
				}
			}
			myThreadDesc.threads = myThreads;
			myThreadDesc.theadCount = i;
			return myThreadDesc;
		}
	}
	
	private class MyThreadDesc{
		//线程当前状态
		private Map<String,String> threadStatus;
		
		public Map<String, String> getThreadStatus() {
			return threadStatus;
		}

		public void setThreadStatus(Map<String, String> threadStatus) {
			this.threadStatus = threadStatus;
		}

		public int getTheadCount() {
			return theadCount;
		}

		public void setTheadCount(int theadCount) {
			this.theadCount = theadCount;
		}

		public List<ThreadInfo> getThreads() {
			return threads;
		}
		//当前线程数量
		private int theadCount;
		//我的线程信息
		private List<ThreadInfo> threads;
	}

}
